@file:JvmMultifileClass
@file:JvmName("TryCatch")

package hos.kotlin

/**
 * <p>Title: TryCatchExt </p>
 * <p>Description:  </p>
 * <p>Company: www.mapuni.com </p>
 *
 * @author : 蔡俊峰
 * @date : 2025-04-11 9:41
 * @version : 1.0
 */


inline fun <R, V> doTryCatchFinally(
    work: () -> R,
    errorHandler: (Throwable) -> R,
    finish: (R?) -> V
): V {
    var result: R? = null
    result = try {
        work()
    } catch (t: Throwable) {
        errorHandler(t)
    } finally {
        @Suppress("ReturnInsideFinallyBlock")
        return finish(result)
    }
}

inline fun <R> doTryCatch(
    work: () -> R,
    errorHandler: (Throwable) -> R,
): R {
    return try {
        work()
    } catch (t: Throwable) {
        errorHandler(t)
    }
}


inline infix fun <T, V> T.runCatch(block: T.() -> V?): Result<V?> {
    return doTryCatch(work = {
        Result.success(block())
    }, errorHandler = {
        Result.failure(it)
    })
}

inline fun <V> runCatch(block: () -> V?): Result<V?> {
    return doTryCatch(work = {
        Result.success(block())
    }, errorHandler = {
        Result.failure(it)
    })
}
